import { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { ArrowLeft } from 'lucide-react';
import './SpecialModelBase.css';
import './PolygonInteriorAngles.css';

/**
 * PolygonInteriorAngles 特殊模板
 * 演示多边形内角和公式：(n-2)×180°
 * 功能：
 * 1. 增加/减少边数（3-10边）
 * 2. 拖动顶点改变形状
 * 3. 显示三角形划分
 * 4. 显示内角和计算
 */

function PolygonInteriorAngles({ modelTitle }) {
  const navigate = useNavigate();
  const canvasRef = useRef(null);
  const [sides, setSides] = useState(5); // 默认五边形
  const [vertices, setVertices] = useState([]);

  // 固定工作空间尺寸
  const WORKSPACE_WIDTH = 800;
  const WORKSPACE_HEIGHT = 500;

  // 初始化多边形顶点位置（圆形分布）
  const initializePolygon = (n) => {
    const centerX = WORKSPACE_WIDTH / 2;
    const centerY = WORKSPACE_HEIGHT / 2;
    const radius = Math.min(WORKSPACE_WIDTH, WORKSPACE_HEIGHT) * 0.3;

    const newVertices = [];
    for (let i = 0; i < n; i++) {
      const angle = (i * 2 * Math.PI) / n - Math.PI / 2; // 从顶部开始
      newVertices.push({
        x: centerX + radius * Math.cos(angle),
        y: centerY + radius * Math.sin(angle),
        id: i
      });
    }
    setVertices(newVertices);
  };

  // 初始化多边形顶点
  useEffect(() => {
    initializePolygon(sides);
  }, [sides]);

  // 绘制画布
  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas || vertices.length === 0) return;

    // 根据屏幕尺寸决定画布尺寸（保持 8:5 比例）
    const windowWidth = window.innerWidth;
    const windowHeight = window.innerHeight;
    const isLandscape = windowWidth > windowHeight;
    let displayWidth, displayHeight;
    
    // 根据横竖屏选择参考尺寸
    const referenceSize = isLandscape ? windowHeight : windowWidth;
    
    if (referenceSize <= 375) {
      // 小屏幕：360x225
      displayWidth = 360;
      displayHeight = 225;
    } else if (referenceSize <= 560) {
      // 中等屏幕：根据参考尺寸线性插值
      // 从 360x225 到 560x350
      const ratio = (referenceSize - 375) / (560 - 375);
      displayWidth = Math.round(360 + ratio * (560 - 360));
      displayHeight = Math.round(225 + ratio * (350 - 225));
    } else {
      // 大屏幕：原始尺寸 800x500
      displayWidth = WORKSPACE_WIDTH;
      displayHeight = WORKSPACE_HEIGHT;
    }
    
    // 设置高DPI
    const dpr = window.devicePixelRatio || 1;
    canvas.width = displayWidth * dpr;
    canvas.height = displayHeight * dpr;
    canvas.style.width = `${displayWidth}px`;
    canvas.style.height = `${displayHeight}px`;
    
    const ctx = canvas.getContext('2d');
    ctx.scale(dpr, dpr);
    
    // 如果不是原始尺寸，需要整体缩放绘制内容
    if (displayWidth !== WORKSPACE_WIDTH) {
      const scale = displayWidth / WORKSPACE_WIDTH;
      ctx.scale(scale, scale);
    }
    
    // 清空画布
    ctx.clearRect(0, 0, WORKSPACE_WIDTH, WORKSPACE_HEIGHT);
    
    // 绘制背景
    ctx.fillStyle = '#ffffff';
    ctx.fillRect(0, 0, WORKSPACE_WIDTH, WORKSPACE_HEIGHT);

    // 绘制三角形划分（虚线）
    ctx.strokeStyle = '#ff9800';
    ctx.lineWidth = 1.5;
    ctx.setLineDash([5, 5]);
    for (let i = 2; i < vertices.length; i++) {
      ctx.beginPath();
      ctx.moveTo(vertices[0].x, vertices[0].y);
      ctx.lineTo(vertices[i].x, vertices[i].y);
      ctx.stroke();
    }
    ctx.setLineDash([]);

    // 绘制多边形
    ctx.strokeStyle = '#333';
    ctx.lineWidth = 2;
    ctx.fillStyle = 'rgba(255, 193, 7, 0.2)';
    ctx.beginPath();
    ctx.moveTo(vertices[0].x, vertices[0].y);
    for (let i = 1; i < vertices.length; i++) {
      ctx.lineTo(vertices[i].x, vertices[i].y);
    }
    ctx.closePath();
    ctx.fill();
    ctx.stroke();

    // 绘制三角形编号
    ctx.font = 'bold 24px Arial';
    ctx.fillStyle = '#ff9800';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    
    for (let i = 1; i < vertices.length - 1; i++) {
      // 计算三角形重心
      const centerX = (vertices[0].x + vertices[i].x + vertices[i + 1].x) / 3;
      const centerY = (vertices[0].y + vertices[i].y + vertices[i + 1].y) / 3;
      ctx.fillText(i.toString(), centerX, centerY);
    }

  }, [vertices]);


  // 增加边数
  const addSide = () => {
    if (sides < 20) {
      setSides(sides + 1);
    }
  };

  // 减少边数
  const removeSide = () => {
    if (sides > 3) {
      setSides(sides - 1);
    }
  };

  // 重置形状
  const resetShape = () => {
    setSides(3); // 重置回三角形
  };

  const triangleCount = sides - 2;

  return (
    <div className="special-model-container">
      {/* 顶部标题栏 */}
      <div className="special-model-top-bar">
        <button
          onClick={() => navigate('/')}
          className="back-button"
          aria-label="返回列表"
        >
          <ArrowLeft size={20} />
          <span className="back-text">返回</span>
        </button>
        <h1 className="app-title">{modelTitle || '多边形内角和'}</h1>
        <img src="/geometry/logo.png" alt="Logo" className="app-logo" />
      </div>

      {/* 主内容区：左中右布局 */}
      <div className="special-model-content">
        {/* 左侧信息面板 */}
        <div className="special-model-info">
          <div className="info-item">
            <span className="info-label">边数</span>
            <span className="info-equals"> = </span>
            <span className="info-value">{sides}</span>
          </div>
          <div className="info-item">
            <span className="info-label">三角形个数</span>
            <span className="info-equals"> = </span>
            <span className="info-value">{triangleCount}</span>
          </div>
          <div className="info-item">
            <span className="info-label">内角和</span>
            <span className="info-equals"> = </span>
            <span className="info-value">{triangleCount}×180°</span>
          </div>
        </div>

        {/* 中间画布区 */}
        <div className="special-model-canvas-wrapper">
          <canvas
            ref={canvasRef}
            className="special-model-canvas"
          />
        </div>

        {/* 右侧控制面板 */}
        <div className="special-model-controls">
          <button
            className="btn"
            onClick={addSide}
            disabled={sides >= 20}
          >
            增加一条边
          </button>
          <button
            className="btn"
            onClick={removeSide}
            disabled={sides <= 3}
          >
            减少一条边
          </button>
          <button
            className="btn"
            onClick={resetShape}
          >
            重置
          </button>
        </div>
      </div>

      {/* 下方信息栏 */}
      <div className="special-model-footer">
        <div className="hint-text">
          <span className="formula-var">n</span>边形内角和 = (<span className="formula-var">n</span>-2)×180°
        </div>
      </div>
    </div>
  );
}

export default PolygonInteriorAngles;

